/*
 * @Author: PanZhangOne
 * @Date: 2017-12-17 13:43:43
 * @Last Modified by:   PanZhangOne
 * @Last Modified time: 2017-12-17 13:43:43
 */
const Topic = require('../models/topic');

/**
 * 创建新帖
 * @param {object} topic 帖子
 */
const createTopic = async (topic) => {
  try {
    let newTopic = await Topic.create({
      title: topic.title,
      content: topic.content,
      authorId: topic.authorId,
      tag: topic.tag
    });

    if (newTopic) {
      return Promise.resolve(newTopic);
    } else {
      return Promise.reject(newTopic);
    }
  } catch (e) {
    return Promise.reject(e);
  }
};

/**
 * 通过id查找帖子
 * @param {ObjectId} topicId 帖子ObjectId
 */
const findTopicById = async (topicId) => {
  try {
    let topic = await Topic.findById(topicId);
    topic.visitCount = topic.visitCount + 1; // 增加主题的阅读量
    topic.save();
    return Promise.resolve(topic);
  } catch (e) {
    return Promise.reject(e);
  }
};

/**
 * 通过id删除帖子
 * @param {ObjectId} topicId 帖子ObjectId
 */
const removeTopicById = async (topicId) => {
  try {
    let topic = await Topic.findById(topicId);

    topic.state = false;
    topic.save()
      .then(newTopic => {
        return Promise.resolve(newTopic);
      })
      .catch(err => {
        return Promise.reject(err);
      });
  } catch (e) {
    return Promise.reject(e);
  }
};

/**
 * 通过帖子ID修改信息
 * @param {ObjectId} topicId 帖子id
 * @param {object} data 要修改的信息
 */
const updateTopicById = async (topicId, data) => {
  try {
    let topic = await Topic.findById(topicId);

    if (topic && topic.state) {
      for (let item in data) {
        topic[item] = data[item];
      }

      topic.save()
        .then(newTopic => {
          return Promise.resolve(newTopic);
        })
        .catch(err => {
          return Promise.reject(err);
        });
    } else {
      return Promise.reject({ success: false, message: '主题不存咋或者被锁定' });
    }
  } catch (e) {
    return Promise.reject(e);
  }
};

module.exports = {
  createTopic,
  findTopicById,
  removeTopicById,
  updateTopicById
};
